public class Solution79 {

    char[][] board;

    int m, n;

    boolean[][] isBeen;

    char[] charArr;

    int[][] directArr = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    private boolean dfs(int i, int j, int ind){
        if(board[i][j] != charArr[ind]){
            return false;
        }
        if(++ind == charArr.length){
            return true;
        }
        for (int k = 0; k < directArr.length; k++) {
            int[] direct = directArr[k];
            int nextI = i + direct[0], nextJ = j + direct[1];
            if( 0 <= nextI && nextI < m &&
                0 <= nextJ && nextJ < n &&
                !isBeen[nextI][nextJ] ) {
                isBeen[nextI][nextJ] = true;
                if(dfs(nextI, nextJ, ind)){
                    return true;
                }
                isBeen[nextI][nextJ] = false;
            }
        }
        return false;
    }

    public boolean exist(char[][] board, String word) {
        this.m = board.length;
        this.n = board[0].length;
        this.board = board;
        this.charArr = word.toCharArray();
        this.isBeen = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                isBeen[i][j] = true;
                if(dfs(i, j, 0)){
                    return true;
                }
                isBeen[i][j] = false;
            }
        }
        return false;
    }
}
